package controllers

import (
	"errors"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"strconv"
	"time"
	"weekFirst/global"
	"weekFirst/models"
	"weekFirst/pkg"
)

type UserController struct {
	beego.Controller
}

func (u *UserController) Login() {
	//u.Ctx.Input.GetData()

	username := u.GetString("username")
	password := u.GetString("password")

	user := models.User{
		Username: username,
	}

	if err := global.Db.Table("users").Where("username = ?", username).Find(&user).Error; err != nil {

		if errors.Is(err, gorm.ErrRecordNotFound) {
			u.CustomAbort(404, "fond")
		} else {
			u.CustomAbort(404, "fond")
		}

		return
	}

	if user.Password != password {
		return
	}

	token, err := pkg.GetJwtToken("2204aaaaaaaaaaa00444", time.Now().Unix(), 86400, strconv.Itoa(int(user.ID)))
	if err != nil {
		return
	}

	models.RedisClient.Set("UserId"+user.Username, token, time.Second*60)

	u.Data["json"] = global.Response{
		Code:    0,
		Message: "用户登录OK",
		Data:    map[string]interface{}{"token": token},
	}

	u.ServeJSON()

}
